<template>
  <nav class="side-menu" :class="{ collapsed: isCollapse && !isMobile }">
    <ul class="menu-list">
      <template v-for="menu in permissionFilteredMenu" :key="menu.path">
        <li v-if="!menu.children" class="menu-item" :class="{ active: activeIndex === menu.path }"
          @click="handleMenuClick(menu.path)">
          <SvgIcon class="menu-icon" size="20px" :icon="menu.icon" />
          <span class="menu-title">{{ menu.title }}</span>
          <el-badge v-if="menu.path === '/warning-center/exception-handling' && alarmStore.unresolvedCount > 0"
            :value="alarmStore.unresolvedCount" class="menu-badge" type="danger" />
        </li>

        <li v-else class="submenu" :class="{ open: openSubmenus.includes(menu.path) }">
          <div class="submenu-title" @click="toggleSubmenu(menu.path)">
            <SvgIcon size="20px" class="menu-icon" :icon="menu.icon" />
            <div class="menu-title">{{ menu.title }}
              <el-badge
                v-if="menu.children?.some(item => item.path === '/warning-center/exception-handling') && alarmStore.unresolvedCount > 0"
                :value="alarmStore.unresolvedCount" class="menu-badge" type="danger" />
            </div>

            <span class="arrow"></span>
          </div>
          <div class="submenu-wrapper" :style="{
            height: openSubmenus.includes(menu.path)
              ? submenuHeight[menu.path] + 'px'
              : '0',
          }">
            <ul class="submenu-list">
              <li v-for="subMenu in menu.children" :key="subMenu.path" class="submenu-item"
                :class="{ active: activeIndex === subMenu.path }" @click="handleMenuClick(subMenu.path)">
                <span class="submenu-text">{{ subMenu.title }}</span>
                <SvgIcon class="new-tab-icon" size="26px" icon="newTag" @click.stop="handleNewTabClick(subMenu.path)" />
              </li>
            </ul>
          </div>
        </li>
      </template>
    </ul>
  </nav>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { usePermissionStore } from "@/stores/permission";
import { useAlarmStore } from "@/stores/alarm";
import { filterMenuByPermissions } from "@/config/menuPermission";
import { menuConfig } from "../../config/menuPermission";

const props = defineProps({
  isCollapse: {
    type: Boolean,
    default: false,
  },
  isMobile: {
    type: Boolean,
    default: false,
  },
});

const router = useRouter();
const route = useRoute();
const permissionStore = usePermissionStore();
const alarmStore = useAlarmStore();
const activeIndex = ref(route.path);
const openSubmenus = ref([]);
const submenuHeight = ref({});

// 更新展开的子菜单
const updateOpenSubmenus = (currentPath) => {
  permissionFilteredMenu.value.forEach((menu) => {
    if (menu.children) {
      const hasActiveChild = menu.children.some(
        (sub) => sub.path === currentPath
      );
      const isOpen = openSubmenus.value.includes(menu.path);

      if (hasActiveChild && !isOpen) {
        openSubmenus.value.push(menu.path);
      }
    }
  });
};

const permissionFilteredMenu = computed(() => {
  return filterMenuByPermissions(menuConfig, permissionStore.userPermissions);
});

// 监听路由变化
watch(
  () => route.path,
  (newPath) => {
    activeIndex.value = newPath;
    updateOpenSubmenus(newPath);
  },
  { immediate: true }
);

onMounted(() => {
  permissionFilteredMenu.value.forEach((menu) => {
    if (menu.children) {
      const itemHeight = 44;
      const gap = 4;
      const totalHeight =
        menu.children.length * itemHeight +
        (menu.children.length - 1) * gap +
        6;
      submenuHeight.value[menu.path] = totalHeight;
    }
  });

  updateOpenSubmenus(route.path);
});

const handleMenuClick = (path) => {
  activeIndex.value = path;
  router.push(path);
};

const handleNewTabClick = (path) => {
  // 获取当前网站的基础URL
  const baseUrl = window.location.origin;
  // 构建完整的URL
  const fullUrl = `${baseUrl}${path}`;
  // 在新标签页中打开
  window.open(fullUrl, '_blank');
};

const toggleSubmenu = (path) => {
  const index = openSubmenus.value.indexOf(path);
  if (index === -1) {
    openSubmenus.value.push(path);
  } else {
    openSubmenus.value.splice(index, 1);
  }
};
</script>

<style lang="scss" scoped>
.side-menu {
  color: #fff;
  height: calc(100% - 3.5rem);
  transition: width 0.3s ease-in-out;
  overflow-y: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;

  .menu-title {
    display: flex;
    align-items: center;
    flex: 1;
  }

  &::-webkit-scrollbar {
    display: none;
  }

  &.collapsed {
    width: 64px;

    .menu-title,
    .arrow {
      display: none;
    }

    .submenu-list {
      display: none;
    }
  }
}

.menu-list {
  padding: 0;
  margin: 0;
  list-style: none;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.menu-item,
.submenu-title {
  display: flex;
  align-items: center;
  padding: 12px;
  height: 44px;
  cursor: pointer;
  transition: background-color 0.3s;
  border-radius: 8px;

  &:hover {
    background-color: rgba(0, 0, 0, 0.2);
    color: #fff;
  }
}

.active {
  background-color: rgba(255, 255, 255, 0.8);
  color: #000;
}

.menu-icon {
  width: 20px;
  height: 20px;
  margin-right: 12px;
}

.arrow {
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid #fff;
  transition: transform 0.3s;
}

.submenu.open .arrow {
  transform: rotate(180deg);
}

.submenu-wrapper {
  transition: height 0.3s ease-in-out;
  overflow: hidden;
}

.submenu-list {
  list-style: none;
  padding: 0;
  margin: 6px 0 0;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.submenu-item {
  margin-left: 24px;
  height: 44px;
  padding: 0 20px;
  line-height: 44px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
  justify-content: space-between;

  &:hover {
    color: #fff;
    background-color: rgba(0, 0, 0, 0.2);
  }

  .submenu-text {
    flex: 1;
  }

  .new-tab-icon {
    opacity: 0;
    /* Initially hidden */
    transition: all 0.15s;
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;

    &:hover {
      opacity: 1;
      background-color: rgba(255, 255, 255, 0.1);
      transform: scale(1.1);
    }
  }
}

.submenu-item:hover .new-tab-icon {
  opacity: 1;
}

.menu-badge {
  display: flex;
  align-items: center;
  transform: scale(0.8) translateX(-10px) translateY(-10px);
}
</style>